package eao;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entity.User;
import entity.UserPicture;

/**
 * Session Bean implementation class EaoUser
 */
@Stateless(mappedName = "eaoUser")
@LocalBean
public class EaoUser {

	@PersistenceContext
	private EntityManager em;
    /**
     * Default constructor. 
     */
    public EaoUser() {
        // TODO Auto-generated constructor stub
    }
    

    public User find(int id) {
        return em.find(User.class, id);
    }

    public User findByEmail(String email) {
        User u = null;
        try{
        	
        	Query q = em.createQuery("SELECT u FROM User as u WHERE u.email=:email", User.class);
        	q.setParameter("email", email);
        	u = (User) q.getSingleResult();
        }catch(NoResultException nre){
        	// this exception occurs when do not found any result to return
        	return null;
        }
        
        return u;
    }
    
    public List<User> list() {
    	return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

    public void create(User user) throws Exception {
        try{
        	em.persist(user);
        	em.flush();
        }catch (Exception e) {
        	throw new Exception(e.getMessage());
		}
    }

    public void update(User user) {
        em.merge(user);
    }

    public void delete(User user) {
        em.remove(em.contains(user) ? user : em.merge(user));
    }

    public static void main(String args[]){
    	EaoUser eu = new EaoUser();
    	
    	for (User u : eu.list()){
    		System.out.println(u.getEmail());
    	}
    }
}
